package com.wande.dataplatform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wande.common.core.exception.ServiceException;
import com.wande.common.core.utils.MapstructUtils;
import com.wande.common.core.utils.StringUtils;
import com.wande.common.mybatis.core.page.PageQuery;
import com.wande.common.mybatis.core.page.TableDataInfo;
import com.wande.common.satoken.utils.LoginHelper;
import com.wande.dataplatform.domain.FillData;
import com.wande.dataplatform.domain.bo.FillDataBo;
import com.wande.dataplatform.domain.vo.FillDataVO;
import com.wande.dataplatform.domain.vo.FillTemplateVO;
import com.wande.dataplatform.mapper.FillDataMapper;
import com.wande.dataplatform.service.IFillDataService;
import com.wande.dataplatform.service.IFillTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 数据填报数据Service业务层处理
 *
 * @author wande
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FillDataServiceImpl implements IFillDataService {

    private final FillDataMapper baseMapper;
    private final IFillTemplateService fillTemplateService;

    /**
     * 查询数据填报数据列表
     */
    @Override
    public TableDataInfo<FillDataVO> queryPageList(FillDataBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FillData> lqw = buildQueryWrapper(bo);
        Page<FillDataVO> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询数据填报数据列表
     */
    @Override
    public List<FillDataVO> queryList(FillDataBo bo) {
        LambdaQueryWrapper<FillData> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FillData> buildQueryWrapper(FillDataBo bo) {
        LambdaQueryWrapper<FillData> lqw = Wrappers.lambdaQuery();
        lqw.eq(FillData::getTenantId, LoginHelper.getTenantId());
        lqw.eq(ObjectUtil.isNotNull(bo.getTemplateId()), FillData::getTemplateId, bo.getTemplateId());
        lqw.eq(StringUtils.isNotBlank(bo.getSubmitStatus()), FillData::getSubmitStatus, bo.getSubmitStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getApprovalStatus()), FillData::getApprovalStatus, bo.getApprovalStatus());
        lqw.eq(ObjectUtil.isNotNull(bo.getSubmitBy()), FillData::getSubmitBy, bo.getSubmitBy());
        lqw.eq(ObjectUtil.isNotNull(bo.getProjectId()), FillData::getProjectId, bo.getProjectId());
        lqw.orderByDesc(FillData::getCreateTime);
        return lqw;
    }

    /**
     * 查询数据填报数据详情
     */
    @Override
    public FillDataVO queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 新增数据填报数据
     */
    @Override
    public Long insertByBo(FillDataBo bo) {
        FillData add = MapstructUtils.convert(bo, FillData.class);
        String tenantId = LoginHelper.getTenantId();
        if (StringUtils.isNotBlank(tenantId)) {
            add.setTenantId(Long.parseLong(tenantId));
        }
        if (StringUtils.isBlank(add.getSubmitStatus())) {
            add.setSubmitStatus("DRAFT");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            return add.getId();
        }
        return null;
    }

    /**
     * 修改数据填报数据
     */
    @Override
    public Boolean updateByBo(FillDataBo bo) {
        FillData update = MapstructUtils.convert(bo, FillData.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 校验并批量删除数据填报数据
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 校验是否可以删除
            for (Long id : ids) {
                FillDataVO vo = queryById(id);
                if (vo != null && !"DRAFT".equals(vo.getSubmitStatus())) {
                    throw new ServiceException("只能删除草稿状态的填报数据");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 提交填报数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitData(Long id) {
        FillData fillData = baseMapper.selectById(id);
        if (fillData == null) {
            throw new ServiceException("填报数据不存在");
        }
        
        if (!"DRAFT".equals(fillData.getSubmitStatus())) {
            throw new ServiceException("只能提交草稿状态的数据");
        }

        // 验证数据
        if (!validateData(fillData.getTemplateId(), fillData.getDataContent())) {
            throw new ServiceException("数据验证失败");
        }

        fillData.setSubmitStatus("SUBMITTED");
        fillData.setSubmitBy(LoginHelper.getUserId());
        fillData.setSubmitTime(LocalDateTime.now());
        
        return baseMapper.updateById(fillData) > 0;
    }

    /**
     * 审批填报数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean approveData(Long id, Boolean approved, String reason) {
        FillData fillData = baseMapper.selectById(id);
        if (fillData == null) {
            throw new ServiceException("填报数据不存在");
        }
        
        if (!"SUBMITTED".equals(fillData.getSubmitStatus())) {
            throw new ServiceException("只能审批已提交的数据");
        }

        if (approved) {
            fillData.setSubmitStatus("APPROVED");
            fillData.setApprovalStatus("APPROVED");
        } else {
            fillData.setSubmitStatus("REJECTED");
            fillData.setApprovalStatus("REJECTED");
            fillData.setRejectReason(reason);
        }
        
        fillData.setApproveBy(LoginHelper.getUserId());
        fillData.setApproveTime(LocalDateTime.now());
        
        // 记录审批历史
        Map<String, Object> history = Map.of(
            "approveBy", LoginHelper.getUserId(),
            "approveTime", LocalDateTime.now().toString(),
            "approved", approved,
            "reason", reason != null ? reason : ""
        );
        fillData.setApprovalHistory(JSONUtil.toJsonStr(history));
        
        return baseMapper.updateById(fillData) > 0;
    }

    /**
     * 验证填报数据
     */
    @Override
    public Boolean validateData(Long templateId, String dataContent) {
        FillTemplateVO template = fillTemplateService.queryById(templateId);
        if (template == null) {
            throw new ServiceException("模板不存在");
        }

        if (StringUtils.isBlank(dataContent)) {
            return false;
        }

        // TODO 根据模板的验证规则验证数据
        log.info("验证填报数据: templateId={}", templateId);
        
        return true;
    }

    /**
     * 导出填报数据
     */
    @Override
    public byte[] exportData(Long id, String format) {
        // TODO 实现数据导出逻辑
        log.info("导出填报数据: id={}, format={}", id, format);
        return new byte[0];
    }

    /**
     * 导入填报数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean importData(Long templateId, byte[] data, String format) {
        // TODO 实现数据导入逻辑
        log.info("导入填报数据: templateId={}, format={}, size={}", templateId, format, data.length);
        return true;
    }
}
